package com.keyboardr.gamerater.fragment;

import java.io.File;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.actionbarsherlock.app.SherlockListFragment;
import com.actionbarsherlock.view.ActionMode;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.keyboardr.gamerater.R;
import com.keyboardr.gamerater.filechooser.FileChooser;
import com.keyboardr.gamerater.fragment.dialog.NewGroupDialogFragment;
import com.keyboardr.gamerater.interfaces.GroupContainer;
import com.keyboardr.gamerater.model.Group;
import com.keyboardr.gamerater.task.LoadFileTask;
import com.keyboardr.gamerater.task.SaveFileTask;

public class GroupsFragment extends SherlockListFragment implements
		OnItemLongClickListener {

	private static final int REQUEST_EXPORT = 100;
	private static final int REQUEST_IMPORT = 101;
	private ActionMode mCurrentActionMode;
	private Group exportingGroup;

	@Override
	public void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		setHasOptionsMenu(true);
	}

	@Override
	public void onStart() {
		super.onStart();
		getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		getListView().setOnItemLongClickListener(this);

		registerForContextMenu(getListView());
		setListAdapter(new ArrayAdapter<Group>(getActivity(),
				android.R.layout.simple_list_item_activated_1,
				((GroupContainer) getActivity()).getGroupList()));

		updateGroupSelection();
	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		((GroupContainer) getActivity()).selectGroup(position);
	}

	public void updateGroupSelection() {
		getListView().setItemChecked(
				((GroupContainer) getActivity()).getSelectedGroupPosition(),
				true);
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		inflater.inflate(R.menu.groups, menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.newGroup:

			new NewGroupDialogFragment().show(getFragmentManager(), null);
			return true;
		case R.id.importGroup:
			importGroup();
			return true;
		}
		return false;
	}

	private void importGroup() {
		Intent fileChooserIntent = new Intent(getActivity(), FileChooser.class);
		fileChooserIntent.putExtra(FileChooser.EXTRA_ALLOW_CREATE, false);
		startActivityForResult(fileChooserIntent, REQUEST_IMPORT);
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view,
			int position, long id) {
		final int pos = position;
		if (mCurrentActionMode != null) {
			return false;
		}

		mCurrentActionMode = getSherlockActivity().startActionMode(
				new ActionMode.Callback() {

					@Override
					public boolean onCreateActionMode(ActionMode mode, Menu menu) {
						mode.setTitle(((GroupContainer) getActivity())
								.getGroupList().get(pos).toString());
						MenuInflater inflater = mode.getMenuInflater();
						inflater.inflate(R.menu.group_context, menu);
						return true;
					}

					@Override
					public boolean onPrepareActionMode(
							ActionMode paramActionMode, Menu paramMenu) {
						return false;
					}

					@Override
					public void onDestroyActionMode(ActionMode paramActionMode) {
						mCurrentActionMode = null;
					}

					@Override
					public boolean onActionItemClicked(ActionMode mode,
							MenuItem paramItem) {
						switch (paramItem.getItemId()) {
						case R.id.deleteGroup:
							showDeleteDialog(pos);
							mode.finish();
							return true;
						case R.id.selectGroup:
							((GroupContainer) getActivity()).selectGroup(pos);
							mode.finish();
							return true;
						case R.id.exportGroup:
							mode.finish();
							return exportGroup(pos);
						}
						return false;
					}
				});
		return true;
	}

	private boolean exportGroup(int pos) {
		exportingGroup = ((GroupContainer) getActivity()).getGroupList().get(
				pos);
		Intent fileChooserIntent = new Intent(getActivity(), FileChooser.class);
		fileChooserIntent.putExtra(FileChooser.EXTRA_ALLOW_CREATE, true);
		startActivityForResult(fileChooserIntent, REQUEST_EXPORT);
		return true;
	}

	public void showDeleteDialog(final int pos) {
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		builder.setMessage("Are you sure you want to delete this group?")
				.setCancelable(false)
				.setPositiveButton("Yes",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								((GroupContainer) getActivity())
										.removeGroup(pos);
							}
						})
				.setNegativeButton("No", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();
					}
				});
		Dialog deleter = builder.create();
		deleter.show();
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case REQUEST_EXPORT:
			if (resultCode == Activity.RESULT_OK) {
				SaveFileTask sft = new SaveFileTask(
						data.getStringExtra(FileChooser.EXTRA_RESULT));
				sft.execute(exportingGroup);
			}
			exportingGroup = null;
			break;
		case REQUEST_IMPORT:
			if (resultCode == Activity.RESULT_OK) {
				LoadFileTask lft = new LoadFileTask(
						(GroupContainer) getActivity());
				File file = new File(
						data.getStringExtra(FileChooser.EXTRA_RESULT));
				lft.execute(file);
			}
			break;
		}
	}
}
